package org.example;

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}
class Solution {
    public String removeDuplicatesII(String s, int k) {
        StringBuilder sb = new StringBuilder(s);
        //栈用来存储相邻且相等的元素的个数
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        for(int i = 1; i < sb.length(); i++){
            if(i > 0 && sb.charAt(i - 1) == sb.charAt(i)){
                int num  =  stack.pop() + 1;
                stack.push(num);
                if(stack.peek() == k){
                    sb.delete(i - k + 1, i + 1);//出现了连续k个字符相等的子串
                    stack.pop();
                    //i需要回退到i - k + 1的位置
                    i = i - k;
                }
            }else{
                stack.push(1);
            }
        }
        return sb.toString();
    }
}